package com.wangyong.bbs.dao;

import java.sql.*;
import java.util.Properties;
import java.io.*;

public class DbUtil {
	
	//驱动程序名 
	private static String driverName = "";
	//数据库用户名 
	private static String userName = "";
	//密码 
	private static String userPasswd = "";
	//数据库名 
	private static String dbName = "";

	//联结字符串 
	private static String dbUrl = "";
	
	//数据库连接
	private static Connection connection = null;
	
	static {
		InputStream inputStream = DbUtil.class
				.getResourceAsStream("DbConfig.properties");
		Properties prop = new Properties();
		try {
			prop.load(inputStream);
			if (inputStream != null) {
				inputStream.close();
			}
			// 驱动程序名
			driverName = prop.getProperty("DriverName").trim();
			// 数据库用户名
			userName = prop.getProperty("UserName").trim();
			// 密码
			userPasswd = prop.getProperty("UserPasswd").trim();
			// 数据库名
			dbName = prop.getProperty("DbName").trim();
			// 联结字符串
			dbUrl = prop.getProperty("DbPreUrl").trim() + dbName + "?user="
					+ userName + "&password=" + userPasswd;
					//"&useUnicode=true&characterEncoding=utf8";
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取数据库连接
	 * @return
	 * @throws Exception
	 */
	public static Connection  getConnection() throws Exception {
		if(connection == null) {
			Class.forName(DbUtil.driverName).newInstance(); 
			connection = DriverManager.getConnection(DbUtil.dbUrl); 
		}
		return connection;
	}
}
